var subTaskId = JSON.parse($.cookie("subTaskId"));
// 切换示例图片显示隐藏
$("#showImage").on('click', function () {
    $("#samplePictures").slideToggle('fast');
    if ($("#fa").attr("class") == "fa fa-chevron-down") {
        $("#fa").attr("class", "fa fa-chevron-up");
    } else if ($("#fa").attr("class") == "fa fa-chevron-up") {
        $("#fa").attr("class", "fa fa-chevron-down");
    }
});
// 删除图片
var deleteimg = new Array();
var rejectImageIdList = new Array();

$("#pendingPictures").on('click', '.deleteimg', function () {
    if ($(this).css("background-image").indexOf("delete_2.png") > 0) {
        $(this).css("background-image", "url('./images/delete_1.png')");
        var imgId = $(this).parent().prev().find('img').attr('data-id'); // 获取不合格图片id
        rejectImageIdList.push(imgId);
        console.log(rejectImageIdList);
    } else if ($(this).css("background-image").indexOf("delete_1.png") > 0) {
        $(this).css("background-image", "url('./images/delete_2.png')");
        var imgId = $(this).parent().prev().find('img').attr('data-id'); // 获取撤销图片id
        for (var i = 0, len = rejectImageIdList.length; i < len; i++) {
            if (rejectImageIdList[i] == imgId) {
                rejectImageIdList.splice(i, 1);
                break;
            }
        }
        console.log(rejectImageIdList);
    }
});
// 查看图片时将不合格的图片在图片查看器里做标识
$("#reviewImagesList").on('click', '.imgs', function () {
    setTimeout(function () {
        for (var i = 0, len = $("#reviewImagesList").children("li").length; i < len; i++) {
            var index = $("body").find(".viewer-list").find("li").eq(i).find('img').attr('data-id');
            for (var j = 0, lens = rejectImageIdList.length; j < lens; j++) {
                if (rejectImageIdList[j] == index) {
                    $("body").find(".viewer-list").find("li").eq(i).find('i').addClass("fa-del");
                }
            }
        }
    }, 500)
})
// 查看大图时选择删除图片
$("body").on('click', '.deleteId', function () {
    var index = $("body").find(".viewer-active").find('img').attr('data-id');
    console.log($("#reviewImagesList").children("li").length);
    for (var i = 0, len = $("#reviewImagesList").children("li").length; i < len; i++) {
        var imgId = $('#reviewImagesList').find("li").eq(i).find('.imgs').find('img').attr('data-id');
        if (imgId == index) {
            if ($.inArray(imgId, rejectImageIdList) == -1) {
                $('#reviewImagesList').find("li").eq(i).find('.delete').find('span').css("background-image", "url('./images/delete_1.png')");
                $("body").find(".viewer-active").find('i').addClass("fa-del");
                rejectImageIdList.push(imgId);
            } else if ($.inArray(imgId, rejectImageIdList) > -1) {
                $('#reviewImagesList').find("li").eq(i).find('.delete').find('span').css("background-image", "url('./images/delete_2.png')");
                $("body").find(".viewer-active").find('i').removeClass("fa-del");
                for (var i = 0, len = rejectImageIdList.length; i < len; i++) {
                    if (rejectImageIdList[i] == imgId) {
                        rejectImageIdList.splice(i, 1);
                        break;
                    }
                }
            }
        }
    }
    console.log(rejectImageIdList);
});

var imgnum = "";

var proRuleDes = [];
// 获取子任务数据
var subTaskData;
$.ajax({
    url: contextPath + "/subtask/" + subTaskId,
    type: 'GET',
    dataType: "json",
    contentType: "application/json",
    success: function (data) {
        if (data.code == 1) {
            console.log(data);
            subTaskData = data.data;
            var deviceTypeId = data.data.deviceTypeId;
            var workOrderTypeId = data.data.workOrderTypeId;
            var projectId = data.data.projectId;
            // 查询流程规则
            $.ajax({
                url: contextPath + "/ProcessRule/queryProcessRuleByDeviceTypeOrderTypeProject",
                type: 'GET',
                data: {"deviceTypeId": deviceTypeId, "workOrderTypeId": workOrderTypeId, "projectId": projectId},
                dataType: 'json',
                contentType: "application/json",
                success: function (data) {
                    if (data.code == 1) {
                        if (data.data == null) {
                            toastr.error("流程规则异常！");
                        } else {
                            console.log(data.data);
                            imgnum = data.data.photoCount;
                            // 示例图
                            var str = '';
                            for (var i = 0, len = data.data.processRuleToImageFileList.length; i < len; i++) {
                                str += '<li>' +
                                    '<img data-original="' + data.data.processRuleToImageFileList[i].path + '" src="' + data.data.processRuleToImageFileList[i].downPath + '" data-id="" alt="' + data.data.processRuleToImageFileList[i].description + '">' +
                                    '<div class="imgDescription">' + data.data.processRuleToImageFileList[i].description + '</div>' +
                                    '</li>';
                                proRuleDes[i] = data.data.processRuleToImageFileList[i].description;
                            }
                            $("#samplePictureList").html(str);
                            subTaskData.processRule = data.data;

                            // 审核图片
                            var str = '';
                            for (var i = 0, len = subTaskData.subTaskImageList.length; i < len; i++) {
                                str +=  '<li>' +
                                    '<div class="imgs">' +
                                        '<img id="Img'+ i + '" subImageId="' + subTaskData.subTaskImageList[i].subImageId +'" qualified="'+ subTaskData.subTaskImageList[i].qualified + '" class = "checkImg" name = "Image" data-original="' + subTaskData.subTaskImageList[i].imagePath + '" src="' + subTaskData.subTaskImageList[i].imagePath + '" data-id="' + subTaskData.subTaskImageList[i].subImageId + '" alt="' + getImageDescription(subTaskData, i) + '"></div>' +
                                        '<div class="imgDescription">' + getImageDescription(subTaskData, i) +
                                        '</div>' ;
                                if(subTaskData.subTaskImageList[i].qualified != 2){
                                    str += '<div><a class="remove" delPath="'+ i + '"style="color:#444444" onclick="removeImg(this)">&nbsp;[替换]</a></div>'+
                                            '</li>';
                                }
                                else{
                                    str += '</li>';
                                }
                            }
                            
                            var a = subTaskData.subTaskImageList.length;
                            if(imgnum == 0){
                                var numStr = '<a class="text" style="color:#000000">可上传任意数量图片，已上传'+ a +'张图片。</a>';
                            }
                            else{
                                var numStr = '<a class="text" style="color:#000000">可上传' + imgnum + '张图片，已上传'+ a +'张图片。</a>';
                            }
                            $("#number").html(numStr);
                            $("#reviewImagesList").html(str);

                            $("#VivaTimeline").html(template('taskProcessInfoTpl', subTaskData));
                            $('.VivaTimeline').vivaTimeline({
                                carousel: false
                            });
                            console.log(subTaskData);
                            $("#basicInformation").html(template('handleBasicInformationTpl', subTaskData));
                            console.log(subTaskData.processRule.additionalBusinessId);
                            // 示例图片查看
                            $('#samplePictureList').viewer({
                                deleteId: false
                            });
                        }
                    }
                },
                error: function (data) {
                    toastr.error(data.message, "请求失败");
                }
            });
        }
    },
    error: function (data) {
        toastr.error(data.message, "请求失败");
    }
});

function getImageDescription(subTask, index) {
    var description = '';

    if (subTask != null) {
        if (index < subTask.processRule.processRuleToImageFileList.length) {
            description = subTask.processRule.processRuleToImageFileList[index].description
        } else {
            var k = index - subTask.processRule.processRuleToImageFileList.length + 1;
            description = subTask.deviceId + '_' + k;
        }
    }

    return description;
}


var submit = "";

var i = "";
var phnum = "";
//提交
$('#submit').on('click',function(){
    var subTaskImageList=[];
    phnum = $(".checkImg").length;
    if(imgnum < phnum && imgnum != 0){
        toastr.error("审核图片数量不得超过示例图片数量");
        return;
    }
    if(imgnum > phnum){
        toastr.error("审核图片数量不得低于示例图片数量");
        return;
    }
    for(i=0;i<$(".checkImg").length;i++){
        var obj={};
        obj.subImageId = $($(".checkImg")[i]).attr('subImageId');
        obj.imagePath = $($(".checkImg")[i]).attr('src');
        obj.deviceId = $("#deviceId").val();
        obj.qualified = $($(".checkImg")[i]).attr('qualified');
        console.log($($(".checkImg")[i]).attr('qualified'));
        if(obj.qualified == 3){
            toastr.error("请替换驳回图片！");
            return;
        }
        console.log(obj);
        subTaskImageList[i] = obj;

    }
    var subTaskBusinessData={};
    console.log($("#latitude").val());
    console.log($("#longitude").val());
    if($("#latitude").val() != null || $("#longitude").val() != null) {
        if (isNaN($("#latitude").val()) || isNaN($("#longitude").val())) {
            {
                toastr.error("经纬度字符串类型不正确！");
                return;
            }
        }
        else {
            if ($("#longitude").val() > 180 || $("#longitude").val() < -180) {
                toastr.error("经度数值不可超出-180—180！");
                return;
            }
            else{
                subTaskBusinessData.longitude = $("#longitude").val();
            }
            if ($("#latitude").val() > 90 || $("#latitude").val() < -90) {
                toastr.error("纬度数值不可超出-90—90区间！");
                return;
            }
            else{
                subTaskBusinessData.latitude = $("#latitude").val();
            }
        }
    }
    console.log($("#latitude").val());
    console.log($("#longitude").val());

    if(isNaN($("#sinr").val()) && $("#sinr").val() != null){
        toastr.error("sinr必须为整数！");
        return;
    }
    else {
        if($("#sinr").val() % 1 != 0 && $("#sinr").val() != null){
            toastr.error("sinr必须为整数！");
            return 0;
        }
        else{
            if($("#sinr").val() != null){
                subTaskBusinessData.sinr = $("#sinr").val();
            }
        }
    }
    if(isNaN($("#rsrp").val()) && $("#rsrp").val() != null){
        toastr.error("rsrp必须为整数！");
        return;
    }
    else {
        if($("#rsrp").val() % 1 != 0 && $("#rsrp").val() != null){
            toastr.error("rsrp必须为整数！");
            return 0;
        }
        else{
            if($("#rsrp").val() != null){
                subTaskBusinessData.rsrp = $("#rsrp").val();
            }
        }
    }
    if(isNaN($("#cellid").val()) && $("#cellid").val() != null){
        toastr.error("cellid必须为整数！");
        return;
    }
    else {
        if($("#cellid").val() % 1 != 0 && $("#cellid").val() != null){
            toastr.error("cellid必须为整数！");
            return 0;
        }
        else{
            if($("#cellid").val() != null){
                subTaskBusinessData.cellid = $("#cellid").val();
            }
        }
    }
    if($("#acquisitionMode").find("option:selected").val() == "true"){
        subTaskBusinessData.acquisitionMode = true;
    }
    else{
        subTaskBusinessData.acquisitionMode =false;
    }
    subTaskBusinessData.devicePosition = $("#deviceAddrs").val();
    if($("#recove").find("option:selected").val() == "true"){
        subTaskBusinessData.recove = true;
    }
    else{
        subTaskBusinessData.recove =false;
    }
    subTaskBusinessData.isInstallDesc = $("#installDesc").val();
    if($("#install").find("option:selected").val() == "true"){
        subTaskBusinessData.install = true;
    }
    else{
        subTaskBusinessData.install = false;
    }
    subTaskBusinessData.faultDesc = $("#faultDesc").val();
    subTaskBusinessData.faultReason = $("#faultReason").val();
    console.log($("#installDesc").val());
    if(subTaskBusinessData.longitude != ""){
        console.log(subTaskBusinessData.longitude);
        subTaskBusinessData.longitude = parseFloat(subTaskBusinessData.longitude).toFixed(7);
        console.log(subTaskBusinessData.longitude);
    }
    else{
        toastr.error("经度不得为空！");
        return;
    }
    if(subTaskBusinessData.latitude != ""){
        console.log(subTaskBusinessData.latitude);
        subTaskBusinessData.latitude = parseFloat(subTaskBusinessData.latitude).toFixed(7);
        console.log(subTaskBusinessData.latitude);
    }
    else{
        toastr.error("纬度不得为空！");
        return;
    }
    submit = true;
    var formData = {
        "subTaskId": subTaskId,
        "subTaskBusinessDataVo":subTaskBusinessData,
        "description": $("#proDescription").text(),
        "subTaskImageVoList":subTaskImageList,
        "submit":submit,
        "uiInputName":''
    };
    console.log(formData);

    $.ajax({
        url: contextPath + '/subtask/submit',
        type: 'POST',
        data: JSON.stringify(formData),
        cache : false,
        contentType: "application/json",
        success: function (D) {
            if(D.code == 1){
                console.log(1)
                toastr.success("任务提交成功!");
                console.log(D)
                location.hash = "#qualitycontrol-assignmentGroup-pending";
            }
            else{
                toastr.error("任务提交失败",D.message);
            }
        },
        error: function (D) {
            toastr.error(D.message);
        }
    });
});

//保存
$('#save').on('click',function(){
    var subTaskImageList=[];
    phnum = $(".checkImg").length;
    if(imgnum < phnum && imgnum != 0){
        toastr.error("审核图片数量不得超过示例图片数量");
        return;
    }

    for(i=0;i<$(".checkImg").length;i++){
        var obj={};
        obj.subImageId = $($(".checkImg")[i]).attr('subImageId');
        obj.imagePath = $($(".checkImg")[i]).attr('src');
        obj.deviceId = $("#deviceId").val();
        obj.qualified = $($(".checkImg")[i]).attr('qualified');
        console.log(obj);
        subTaskImageList[i] = obj;
    }
    var subTaskBusinessData={};
    console.log($("#latitude").val());
    console.log($("#longitude").val());
    if($("#latitude").val() != null || $("#longitude").val() != null) {
        if (isNaN($("#latitude").val()) || isNaN($("#longitude").val())) {
            {
                toastr.error("经纬度字符串类型不正确！");
                return;
            }
        }
        else {
            if ($("#longitude").val() > 180 || $("#longitude").val() < -180) {
                toastr.error("经度数值不可超出-180—180！");
                return;
            }
            else{
                subTaskBusinessData.longitude = $("#longitude").val();
            }
            if ($("#latitude").val() > 90 || $("#latitude").val() < -90) {
                toastr.error("纬度数值不可超出-90—90区间！");
                return;
            }
            else{
                subTaskBusinessData.latitude = $("#latitude").val();
            }
        }
    }
    console.log(subTaskBusinessData.latitude);
    console.log($("#latitude").val());
    console.log($("#longitude").val());
    if(isNaN($("#sinr").val()) && $("#sinr").val() != null){
        toastr.error("sinr必须为整数！");
        return;
    }
    else {
        if($("#sinr").val() % 1 != 0 && $("#sinr").val() != null){
            toastr.error("sinr必须为整数！");
            return 0;
        }
        else{
            if($("#sinr").val() != null){
                subTaskBusinessData.sinr = $("#sinr").val();
            }
        }
    }
    if(isNaN($("#rsrp").val()) && $("#rsrp").val() != null){
        toastr.error("rsrp必须为整数！");
        return;
    }
    else {
        if($("#rsrp").val() % 1 != 0 && $("#rsrp").val() != null){
            toastr.error("rsrp必须为整数！");
            return 0;
        }
        else{
            if($("#rsrp").val() != null){
                subTaskBusinessData.rsrp = $("#rsrp").val();
            }
        }
    }
    if(isNaN($("#cellid").val()) && $("#cellid").val() != null){
        toastr.error("cellid必须为整数！");
        return;
    }
    else {
        if($("#cellid").val() % 1 != 0 && $("#cellid").val() != null){
            toastr.error("cellid必须为整数！");
            return 0;
        }
        else{
            if($("#cellid").val() != null){
                subTaskBusinessData.cellid = $("#cellid").val();
            }
        }
    }

    if($("#acquisitionMode").find("option:selected").val() == "true"){
        subTaskBusinessData.acquisitionMode = true;
    }
    else{
        subTaskBusinessData.acquisitionMode =false;
    }

    subTaskBusinessData.devicePosition = $("#deviceAddrs").val();

    if($("#recove").find("option:selected").val() == "true"){
        subTaskBusinessData.recove = true;
    }
    else{
        subTaskBusinessData.recove =false;
    }

    subTaskBusinessData.isInstallDesc = $("#installDesc").val();

    if($("#install").find("option:selected").val() == "true"){
        subTaskBusinessData.install = true;
    }
    else{
        subTaskBusinessData.install = false;
    }

    subTaskBusinessData.faultDesc = $("#faultDesc").val();
    subTaskBusinessData.faultReason = $("#faultReason").val();
    console.log($("#installDesc").val());
    if(subTaskBusinessData.longitude != ""){
        console.log(subTaskBusinessData);
        subTaskBusinessData.longitude = parseFloat(subTaskBusinessData.longitude).toFixed(7);
        console.log(subTaskBusinessData);
    }


    if(subTaskBusinessData.latitude != ""){
        console.log(subTaskBusinessData.latitude);
        subTaskBusinessData.latitude = parseFloat(subTaskBusinessData.latitude).toFixed(7);
        console.log(subTaskBusinessData.latitude);

    }
    submit = false;
    var formData = {
        "subTaskId": subTaskId,
        "subTaskBusinessDataVo":subTaskBusinessData,
        "description": $("#proDescription").text(),
        "subTaskImageVoList":subTaskImageList,
        "submit":submit
    };
    console.log(formData);

    $.ajax({
        url: contextPath + '/subtask/submit',
        type: 'POST',
        data: JSON.stringify(formData),
        cache : false,
        contentType: "application/json",
        success: function (D) {
            if(D.code == 1){
                console.log(1)
                toastr.success("任务保存成功!");
                console.log(D)
                location.hash = "#qualitycontrol-assignmentGroup-pending";
            }
            else{
                toastr.error("任务保存失败",D.message);
            }
        },
        error: function (D) {
            toastr.error(D.message);
        }
    });
});
